import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.filesystem.File;
import flash.net.FileFilter;
import flash.net.FileReference;

import mx.collections.ArrayList;
import mx.controls.Alert;

private var _fileReferenece:FileReference;
private var _fileType:int;
private var _destFileData:String;
private var _changedFileData:String;
private var _dictionaryData:Array = [];

private function initApplication():void{
	trace( 'init' );
}
private function initFileReference():void{
	if( _fileReferenece ){
		_fileReferenece.removeEventListener( Event.SELECT, onSelectFile );
		_fileReferenece.removeEventListener( Event.COMPLETE, onCompleteLoadFile );
		_fileReferenece.removeEventListener( IOErrorEvent.IO_ERROR, onError );
	}
	
	_fileReferenece = new FileReference;
	_fileReferenece.addEventListener( Event.SELECT, onSelectFile );
	_fileReferenece.addEventListener( Event.COMPLETE, onCompleteLoadFile );
	_fileReferenece.addEventListener( IOErrorEvent.IO_ERROR, onError );
}
private function onSelectFile( $e:Event ):void{
	trace( 'open' );
	setFileURLToTextArea();
	_fileReferenece.load();
}
private function setFileURLToTextArea():void{
	switch( _fileType ){
	case 1:
		destFilePath.text = _fileReferenece.name;
		break;
	case 2:
		dictionaryPath.text = _fileReferenece.name;
		break;
	}
}
private function onCompleteLoadFile( $e:Event ):void{
	trace( 'load complete---------------------------------------------------------------------\n' );
	trace( 'file type : ' + _fileType );
	trace( _fileReferenece.data );
	setData();
}
private function setData():void{
	switch( _fileType ){
	case 1:
		setDestFileData();
		break;
	case 2:
		setDictionaryData();
		break;
	}
}
private function setDestFileData():void{
	_destFileData = String( _fileReferenece.data );
	contentView.text = _destFileData;
}
private function setDictionaryData():void{
	var i:int, j:int, temp:Array, dictionaryData:String, data:Object;
	
	dictionaryData = String( _fileReferenece.data );
	dictionaryData.replace( /[\t\r\v\f]/g, '' );
	temp = dictionaryData.split( /\n/ );
	_dictionaryData.shift();
	_dictionaryData.shift();
	for( i = 0, j = temp.length ; i < j ; ++i ){
		data = getWordData( temp[i] );
		if( data ){
			_dictionaryData[_dictionaryData.length] = data;
		}
	}
	_dictionaryData.sortOn( 'length', Array.NUMERIC );
	_dictionaryData.reverse();
	wordsList.dataProvider = new ArrayList( _dictionaryData );
}
private function getWordData( $data:String ):Object{
	var result:Object, temp:Array;
	
	temp = $data.split( ',' );
	if( temp[0] === '' && temp[1] === undefined ){}else{
		result = {en:temp[0], kr:temp[1], length:temp[0].length};
		return result;
	}
	
	return null;
}
private function onError( $e:IOErrorEvent ):void{
	trace( 'error ' + $e.text );
}
private function onClickBtnOpenDestFile():void{
	initFileReference();
	setFileTypeDestFile();
	_fileReferenece.browse( getFileFilter() );
}
private function setFileTypeDestFile():void{
	_fileType = 1;
}
private function getFileFilter():Array{
	var result:Array;
	
	switch( _fileType ){
	case 1:
		result = [new FileFilter( 'text', '*.txt' )];
		break;
	case 2:
		result = [new FileFilter( 'csv', '*.csv' )];
		break;
	}
	
	return result;
}
private function onClickBtnDictionary():void{
	initFileReference();
	setFileTypeDictionary();
	_fileReferenece.browse( getFileFilter() );
}
private function setFileTypeDictionary():void{
	_fileType = 2;
}

private function onClickBtnChangeWord():void{
	if( _destFileData === '' || _destFileData === null ){
		Alert.show( '원본 텍스트 파일을 불러온 후 눌러 주세요.', '불러온 텍스트 파일이 없습니다.' );
		return;
	}
	if( _dictionaryData === null || _dictionaryData.length === 0 ){
		Alert.show( '단어 csv 파일을 불러온 후 눌러 주세요.', '불러온 단어 csv 파일이 없습니다.' );
		return;
	}
	
	initFileReference();
	_fileReferenece.removeEventListener( Event.SELECT, onSelectFile );
	_fileReferenece.removeEventListener( Event.COMPLETE, onCompleteLoadFile );
	
	_changedFileData = getApplyDictionaryWords( _changedFileData );
	_changedFileData = getApplyNewLine( _changedFileData );
//	contentView.content = _changedFileData;
	save( _changedFileData );
}
private function getApplyDictionaryWords( $target:String ):String{
	var i:int, j:int, pattern:RegExp, word:String, wordData:Object, result:String, matchResult:Array;
	
	result = contentView.text;
	for( i = 0, j = _dictionaryData.length ; i < j ; ++i ){
		wordData = _dictionaryData[i];
		if( wordData.en === null || wordData.kr === undefined ){}else{
			word = wordData.en;
			pattern = new RegExp( '\\b' + word + '\\b', 'gi' );
			matchResult = result.match( pattern );
			trace( 'word : ' + word + '\ result = ' + matchResult.length );
			result = result.replace( pattern, function():String{
				return getColoringWord( arguments[0], wordData.kr );
			} );
		}
	}
	
	return result;
}

private function getApplyDictionaryWord( $target:String ):String{
	var i:int, j:int, pattern:RegExp, word:String, wordData:Object, result:String, matchResult:Array;
	
	result = _destFileData;
	wordData = _dictionaryData[1];
//	word = wordData.en;
	word = 'What you need for this book';
//	pattern = /\bWhat you need for this book\b/gi
	pattern = new RegExp( '\\bWhat you need for this book\\b', 'gi' );
	matchResult = result.match( pattern );
	trace( 'word : ' + word + '\ result = ' + matchResult.length );
	result = result.replace( pattern, function():String{
		return getColoringWord( arguments[0], wordData.kr );
	} );
	
	return result;
}


private function getApplyNewLine( $target:String ):String{
	return $target.replace( /\r/g, '<br>' );
}
private function save( $data:String ):void{
	_fileReferenece.save( _changedFileData, 'result' );
}
private function getColoringWord( $en:String, $kr:String ):String{
	var result:String;
	
	result = '<font color="#0000ff">' + $en + '</font>' + ':' + '<font color="#ff0000">' + $kr + '</font>';
	
	return result;
}

private function onSelectWord():void{
	if( contentView.text ){
		coloringSelectedWords();
	}
}
private function coloringSelectedWords():void{
//	var str:String, pattern:RegExp;
//	
//	str = contentView.text;
//	pattern = new RegExp( '\\b' + wordsList.selectedItem.en + '\\b', 'gi' );
//	str = str.replace( pattern, function():String{
//		return getColoringWord2( arguments[0] );
//	} );
//	contentView.content = str;
}

private function getColoringWord2( $en:String ):String{
	var result:String;
	
	result = '<s:span fontSize="20">' + $en + '</s:span>';
	
	return result;
}